package com.xbongbong.pro.statistics.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.pojo.dto.ChartUpdateAveDTO;
import com.xbongbong.paas.pojo.dto.PaasFormDataEsInitDTO;
import com.xbongbong.paas.pojo.dto.PrintLogDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsInitVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.statistic.pojo.dto.ChartEditDTO;
import com.xbongbong.pro.statistic.pojo.dto.InitAllDTO;
import com.xbongbong.pro.statistic.pojo.dto.LogStashEditDTO;
import com.xbongbong.pro.statistic.pojo.dto.MappingInitDTO;
import com.xbongbong.pro.statistic.pojo.dto.ReInitDataDTO;
import com.xbongbong.pro.statistic.pojo.dto.UpdateDataDTO;
import com.xbongbong.pro.statistic.pojo.vo.DataInitVO;
import com.xbongbong.pro.statistic.service.ChartService;
import com.xbongbong.pro.statistic.service.DataWarehouseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author 梁鲁江
 * @version v1.0
 * @date 2019/2/12 13:52
 * @since v1.0
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/chart")
public class ChartDataWarehouseController {

    @Resource
    private DataWarehouseService dataWarehouseService;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private ChartService chartService;

    private static final Logger LOG = LoggerFactory.getLogger(ChartDataWarehouseController.class);
    @RequestMapping(value = "/initData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String initData(@RequestBody @Valid ChartEditDTO chartEditDTO, BindingResult br) {
        XbbResponse<DataInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            // ----------------------------------repeat post----------------------------------------------
            // 判断是否跳过重复提交校验
            if (!Boolean.TRUE.equals(chartEditDTO.getIgnoreConCheck())) {
                //重复提交校验
                if (!paasRedisHelper.checkConcurrentLock(chartEditDTO)) {
                    response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                    return JSON.toJSONString(response);
                }
            }
            // ----------------------------------repeat post----------------------------------------------
            try {
                DataInitVO dataInitVO = dataWarehouseService.initData(chartEditDTO);
                response = new XbbResponse<>(dataInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    @RequestMapping(value = "/init/reInitBIData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String reInitBIData(@RequestBody @Valid ReInitDataDTO reInitDataDTO, BindingResult br) {
        XbbResponse<DataInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            // ----------------------------------repeat post----------------------------------------------
            // 判断是否跳过重复提交校验
            if (!Boolean.TRUE.equals(reInitDataDTO.getIgnoreConCheck())) {
                //重复提交校验
                if (!paasRedisHelper.checkConcurrentLock(reInitDataDTO)) {
                    response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                    return JSON.toJSONString(response);
                }
            }
            // ----------------------------------repeat post----------------------------------------------
            try {
                if(!proBaseConfig.getXbbCode().equals(reInitDataDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                LOG.info("start========"+ System.currentTimeMillis());
                DataInitVO dataInitVO = dataWarehouseService.reInitBIData(reInitDataDTO);
                response = new XbbResponse<>(dataInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    @RequestMapping(value = "/init/reInitCustomerBIData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String reInitCustomerBIData(@RequestBody @Valid MappingInitDTO mappingInitDTO, BindingResult br) {
        XbbResponse<DataInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            // ----------------------------------repeat post----------------------------------------------
            // 判断是否跳过重复提交校验
            if (!Boolean.TRUE.equals(mappingInitDTO.getIgnoreConCheck())) {
                //重复提交校验
                if (!paasRedisHelper.checkConcurrentLock(mappingInitDTO)) {
                    response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                    return JSON.toJSONString(response);
                }
            }
            // ----------------------------------repeat post----------------------------------------------
            try {
                if(!proBaseConfig.getXbbCode().equals(mappingInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                DataInitVO dataInitVO = dataWarehouseService.reInitCustomerBIData(mappingInitDTO);
                response = new XbbResponse<>(dataInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
    
    @RequestMapping(value = "/init/updateData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateData( @Valid UpdateDataDTO updateDataDTO, BindingResult br) {
        XbbResponse<DataInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            // ----------------------------------repeat post----------------------------------------------
            // 判断是否跳过重复提交校验
            if (!Boolean.TRUE.equals(updateDataDTO.getIgnoreConCheck())) {
                //重复提交校验
                if (!paasRedisHelper.checkConcurrentLock(updateDataDTO)) {
                    response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                    return JSON.toJSONString(response);
                }
            }
            // ----------------------------------repeat post----------------------------------------------
            try {
                if(!proBaseConfig.getXbbCode().equals(updateDataDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                //TODO  更新接口先改成和原来一样
                DataInitVO dataInitVO = dataWarehouseService.updateBIData(updateDataDTO);
                response = new XbbResponse<>(dataInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
    @RequestMapping(value = "/deleteAllData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Deprecated
    public String deleteAllData(@RequestBody @Valid MappingInitDTO mappingInitDTO, BindingResult br) {
        XbbResponse<DataInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            // ----------------------------------repeat post----------------------------------------------
            // 判断是否跳过重复提交校验
            if (!Boolean.TRUE.equals(mappingInitDTO.getIgnoreConCheck())) {
                //重复提交校验
                if (!paasRedisHelper.checkConcurrentLock(mappingInitDTO)) {
                    response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                    return JSON.toJSONString(response);
                }
            }
            // ----------------------------------repeat post----------------------------------------------
            try {
                if(!proBaseConfig.getXbbCode().equals(mappingInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                DataInitVO dataInitVO = dataWarehouseService.deleteAllData(mappingInitDTO);
                response = new XbbResponse<>(dataInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     *  /pro/v1/chart/initLogStash
     * {"frontDev":"1","platform":"web","corpid":"xbbxing","userId":"xiao001","xbbCode":123456,"user":"test","password":"123456","hosts":["es-cn-oew1tkvx0000r7vpp.elasticsearch.aliyuncs.com"],"version":"xbbProTest2","port":30001}
     * @param logStashEditDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/initLogStash", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String initLogStash(@RequestBody @Valid LogStashEditDTO logStashEditDTO, BindingResult br) {
        XbbResponse<DataInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            // ----------------------------------repeat post----------------------------------------------
            // 判断是否跳过重复提交校验
            if (!Boolean.TRUE.equals(logStashEditDTO.getIgnoreConCheck())) {
                //重复提交校验
                if (!paasRedisHelper.checkConcurrentLock(logStashEditDTO)) {
                    response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                    return JSON.toJSONString(response);
                }
            }
            // ----------------------------------repeat post----------------------------------------------
            try {
                DataInitVO dataInitVO = dataWarehouseService.initLogStash(logStashEditDTO);
                response = new XbbResponse<>(dataInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    @RequestMapping(value = "/initAllData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String initAllData(@RequestBody @Valid InitAllDTO initAllDTO, BindingResult br) {
        XbbResponse<DataInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            // ----------------------------------repeat post----------------------------------------------
            // 判断是否跳过重复提交校验
            if (!Boolean.TRUE.equals(initAllDTO.getIgnoreConCheck())) {
                //重复提交校验
                if (!paasRedisHelper.checkConcurrentLock(initAllDTO)) {
                    response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                    return JSON.toJSONString(response);
                }
            }
            // ----------------------------------repeat post----------------------------------------------
            try {
                if(!proBaseConfig.getXbbCode().equals(initAllDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                DataInitVO dataInitVO = dataWarehouseService.initAllData(initAllDTO);
                response = new XbbResponse<>(dataInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    @RequestMapping(value = "/setPrintLog", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String setPrintLog(@RequestBody @Valid PrintLogDTO printLogDTO, BindingResult br) throws Exception {
        XbbResponse<String> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(printLogDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                xbbElasticsearchRestTemplate.setPrintLog(printLogDTO.getPrintLog());
                response = new XbbResponse<>(printLogDTO.getPrintLog().toString());
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    @RequestMapping(value = "/init/formDataInitTest", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String formDataInit(@RequestBody @Valid PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;

        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasPrintSaveVO = null;
                if(Objects.equals(1,paasFormDataEsInitDTO.getSaasMark())){
                     paasPrintSaveVO = dataWarehouseService.init(paasFormDataEsInitDTO);
                }else {
                    paasPrintSaveVO = dataWarehouseService.initAll(paasFormDataEsInitDTO);
                }
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
    @RequestMapping(value = "/init/initNewBiMapping", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String initNewBiMapping(@RequestBody @Valid MappingInitDTO mappingInitDTO, BindingResult br) {
        XbbResponse<DataInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            // ----------------------------------repeat post----------------------------------------------
            // 判断是否跳过重复提交校验
            if (!Boolean.TRUE.equals(mappingInitDTO.getIgnoreConCheck())) {
                //重复提交校验
                if (!paasRedisHelper.checkConcurrentLock(mappingInitDTO)) {
                    response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                    return JSON.toJSONString(response);
                }
            }
            // ----------------------------------repeat post----------------------------------------------
            try {
                if(!proBaseConfig.getXbbCode().equals(mappingInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                DataInitVO dataInitVO = dataWarehouseService.initNewBiMapping(mappingInitDTO);
                response = new XbbResponse<>(dataInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
    @RequestMapping(value = "/init/initAllBiMapping", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String initAllBiMapping(@RequestBody @Valid MappingInitDTO mappingInitDTO, BindingResult br) {
        XbbResponse<DataInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            // ----------------------------------repeat post----------------------------------------------
            // 判断是否跳过重复提交校验
            if (!Boolean.TRUE.equals(mappingInitDTO.getIgnoreConCheck())) {
                //重复提交校验
                if (!paasRedisHelper.checkConcurrentLock(mappingInitDTO)) {
                    response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                    return JSON.toJSONString(response);
                }
            }
            // ----------------------------------repeat post----------------------------------------------
            try {
                if(!proBaseConfig.getXbbCode().equals(mappingInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                DataInitVO dataInitVO = dataWarehouseService.initAllBiMapping(mappingInitDTO);
                response = new XbbResponse<>(dataInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
    /**
     * 更新自定义表中的数据，加上默认平均线1
     */
    @RequestMapping(value = "/updateAverageLine", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateAverageLine(@RequestBody @Valid ChartUpdateAveDTO chartUpdateAveDTO, BindingResult br) {
        XbbResponse<String> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(chartUpdateAveDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                chartService.chartUpdate4Ave(chartUpdateAveDTO);
                response = new XbbResponse<>();
            }catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
